package main

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/registry"
	"github.com/micro/go-plugins/registry/consul"
	"log"
	"net/http"
)

func main() {
	log.Println("服务器端开始启动============")
	consulReg := consul.NewRegistry(
		registry.Addrs("122.51.93.207:8500"),
	)

	//其实下面这段代码的意义就是启动的时候把服务注册进去,并且启动webservier
	httpserver := micro.NewService(
		micro.Name("clientService"), //注册进consul服务中的service名字
		micro.Address(":10002"),     //注册进consul服务中的端口,也是这里我们gin的server地址
		micro.Registry(consulReg),   //注册到哪个服务器上的consul中
	)
	httpserver.Init() //加了这句就可以使用命令行的形式去设置我们一些启动的配置

	sClient := httpserver.Client()
	sRequest := sClient.NewRequest("serviceService", "Greeter.Hello", "jjjjohe", client.WithContentType("application/json"))
	var response string
	if err := sClient.Call(context.TODO(), sRequest, &response); err != nil {
		log.Println(err)
	}

	log.Println(response)
	/*	user := new(User)
		//集成gin
		router := gin.Default()
		router.HandleMethodNotAllowed = true
		router.NoMethod(func(c *gin.Context) {
			c.JSON(http.StatusMethodNotAllowed, gin.H{"result": false, "error": "Method Not Allowed"})
			return
		})
		router.NoRoute(func(c *gin.Context) {
			c.JSON(http.StatusNotFound, gin.H{"result": false, "error": "Endpoint Not Found"})
			return
		})
		router.POST("/login", user.Login)
		router.POST("/login2", user.Login)

		httpserver.Handle("/", router)*/

	//httpserver.Run()
	log.Println("服务器端启动成功============")
}

type User struct{}

func (u *User) Login(c *gin.Context) {
	log.Print("Received Login API request")
	var req map[string]interface{}
	err := json.NewDecoder(c.Request.Body).Decode(&req)
	if err != nil {
		c.Error(err)
		c.JSON(http.StatusInternalServerError, gin.H{"result": false, "error": err.Error()})
		return
	}
	if req["username"] == nil {
		err := errors.New("Field username is rquired.")
		c.Error(err)
		c.JSON(http.StatusInternalServerError, gin.H{"result": false, "error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"result": true, "data": req})
}

type TestUser struct {
	Name string `json:"name" form:"first_name"`
	Msg  string `json:"msg" form:"last_name"`
}
